package com.xzr.hospitalregister.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.xzr.hospitalregister.R;
import com.xzr.hospitalregister.adapter.CallNumberAdapter;
import com.xzr.hospitalregister.base.BaseActivity;
import com.xzr.hospitalregister.config.HttpUrl;
import com.xzr.hospitalregister.entity.CallNumberListItem;
import com.xzr.hospitalregister.util.DataCleanManager;
import com.xzr.hospitalregister.util.DividerItemDecoration;
import com.xzr.hospitalregister.util.GetTokenFromClientAPK;
import com.xzr.hospitalregister.util.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by Administrator on 2018/1/24 0024.
 */

public class CallNumberActivity extends BaseActivity {
    private TextView tv_time,tv_mTime,text1,te_jh_gdt,tv_content;
    private TextToSpeech textToSpeech;
    private MediaPlayer music = null;// 播放器引用

    private static final int msgKey1 = 1;
    private static final int msgKey2 = 5;
    public boolean isSelected =true;
    private RecyclerView mRecyclerview;
    private CallNumberAdapter callNumberAdapter = null;
    private List<CallNumberListItem> data = new ArrayList<>();

    private Button but_ertongbjb;
    private String  deviceId;
    public String newName;

    SharedPreferences sp1;
    int status2;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        getSupportActionBar().hide();// 隐藏ActionBar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//remove notification bar  即全屏
        setContentView(R.layout.activity_callnumber);
        initWidget();
        initData();
//        textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
//            @Override
//            public void onInit(int status) {
//                if (status == textToSpeech.SUCCESS) {
//                    int result = textToSpeech.setLanguage(Locale.CHINA);
//                    if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
//                            && result != TextToSpeech.LANG_AVAILABLE){
////                        Toast.makeText(CallNumberActivity.this, "TTS暂时不支持这种语音的朗读！",
////                                Toast.LENGTH_SHORT).show();
//                        Toast.makeText(getApplicationContext(), "TTS暂时不支持这种语音的朗读！",
//                                Toast.LENGTH_SHORT).show();
//                    }
//                }
//            }
//        });
        deviceId =GetTokenFromClientAPK.getMacAddress1();
        if (!TextUtils.isEmpty(deviceId)){
            deviceId = deviceId.replaceAll("[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……& amp;*（）——+|{}【】‘；：”“’。，、？|-]", ""); //去标点符号
            deviceId = deviceId.toLowerCase();//大写转换成小写
            Toast.makeText(CallNumberActivity.this,deviceId,Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(CallNumberActivity.this,"MAC地址为空",Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void initWidget() {
        super.initWidget();
        text1 = (TextView) findViewById(R.id.text1);
        te_jh_gdt = (TextView) findViewById(R.id.te_jh_gdt);
        te_jh_gdt.setSelected(true);//如果textview不滚动就加上这句代码
//        tv_time = (TextView) findViewById(R.id.tv_time);
//        tv_mTime = (TextView) findViewById(R.id.tv_mTime);
//        new TimeThread().start();
        new TimeThreadjh().start();
        tv_content = (TextView) findViewById(R.id.tv_custom_content);
        tv_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rename();
            }
        });
        SharedPreferences sp = getSharedPreferences("HosSet", MODE_PRIVATE);
        String username =sp.getString("hosValue","博爱县妇幼保健院");
        tv_content.setText(username);

        mRecyclerview = (RecyclerView) findViewById(R.id.recyclerview_dthz);
        but_ertongbjb = (Button) findViewById(R.id.but_ertongbjb);
    }

    @Override
    public void initData() {
        super.initData();
        DataCleanManager.clearAllCache(this);//清除缓存
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDateStr = sdf.format(new Date());
        String[] nowDateStrSplits = nowDateStr.split("-");
//        tv_time.setText(nowDateStr);
        SharedPreferences sp4 = getSharedPreferences("YuYin", MODE_PRIVATE);
        String yuYinValueGdt =sp4.getString("yuYinValue","");
        text1.setText(yuYinValueGdt);
        try {
            JSONObject jsonObject = new JSONObject(getIntent().getStringExtra("jsonData"));
            JSONArray jsonData = jsonObject.getJSONArray("rows");
            for (int i = 0; i < jsonData.length(); i++) {
                JSONObject jsonObject1 = jsonData.getJSONObject(i);
                data.add(new CallNumberListItem(jsonObject1.getString("ROOMNAME"),jsonObject1.getString("DZ"),jsonObject1.getString("HJ"),jsonObject1.getString("JZ")));
                but_ertongbjb.setText(jsonObject1.getString("NAME"));
            }
            Log.e("TAG","获取到的jsonObject +++"+jsonObject);
            Log.e("TAG","获取到的jsonData +++"+jsonData);
            Log.e("TAG","获取到的(String) msg.obj +++"+getIntent().getStringExtra("jsonData"));
            if (data.size() > 0) {
                // TODO: 2018/2/5 0005 即有待读数据时，启动读音服务
                for (int j = 0; j < data.size(); j++) {
                    if (!TextUtils.isEmpty(data.get(j).getHujiao())) {
//                        text1.setText("请，" + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊，" + data.get(j).getZhunbei() + "准备就诊");
//                        Log.e("TAG", "滚动条+++" + "请，" + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊，" + data.get(j).getZhunbei() + "准备就诊");
                        text1.setText("请，" + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊");
                        Log.e("TAG", "滚动条+++" + "请，" + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊");

//                        PlayMusic(R.raw.yuyin);
//                        for (int k = 0; k <2 ; k++) {
//                            textToSpeech.speak(text1.getText().toString(),
//                                    TextToSpeech.QUEUE_ADD, null);
                            ////////////////////
                            SharedPreferences sp3 = getSharedPreferences("YuYin", MODE_PRIVATE);
                            final String yuYinValue =sp3.getString("yuYinValue","");
                            Log.e("TAG","SharedPreferences sp3获得的语音朗读+++++++++++++++++++++"+yuYinValue);
//                            if (status2 == TextToSpeech.SUCCESS) {
//                                int result = textToSpeech.setLanguage(Locale.CHINA);
//                                if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
//                                        && result != TextToSpeech.LANG_AVAILABLE){
//                                    Toast.makeText(getApplicationContext(), "TTS语音绑定失败！",
//                                            Toast.LENGTH_SHORT).show();
//                                }else {
//                                    textToSpeech.speak(yuYinValue,
//                                            TextToSpeech.QUEUE_ADD, null);
//                                }
//                            }
                            /////////////////
                            ///////////////
                            textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
                                @Override
                                public void onInit(int status) {
                                    if (status == textToSpeech.SUCCESS) {
                                        int result = textToSpeech.setLanguage(Locale.CHINA);
                                        if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
                                                && result != TextToSpeech.LANG_AVAILABLE){
                                            Toast.makeText(getApplicationContext(), "TTS暂时不支持这种语音的朗读！",
                                                    Toast.LENGTH_SHORT).show();
                                        }else {
                                            PlayMusic(R.raw.yuyin);
                                            for (int k = 0; k <2 ; k++) {
                                            textToSpeech.speak(yuYinValue,
                                                    TextToSpeech.QUEUE_ADD, null);}
                                        }
                                    }
                                }
                            });
                            //////////////////
                            /////////////////////
                            ////////////////////
//                        }
                    }
//                    else if  (!TextUtils.isEmpty(data.get(j).getJiuzhen()))
//                        text1.setText(data.get(j).getJiuzhen() + "在" + data.get(j).getZhenshi() + "就诊中，" + data.get(j).getZhunbei() + "准备就诊");
                }
            }
            showAllMotherSonInfo();
            System.out.println("YCMotherSonInfoselectFragment   " + getIntent().getStringExtra("jsonData"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
//    private String mac = "jj344kmo3k23";
//    private String mac = "dcc0db78ad38";
//    private String mac = "dcc0db78aa5b";
    private String mac = "00606ec858de";//儿童保健部—叫号
    public void getMotherYFXXTKFromRemote(){
        data.clear();
//        HttpRequest.getInstance().getRequest(HttpUrl.MEN_ZHEN_GUA_HAO + "?param={\"mac\":\"" + mac + "\"+,\"flag\":\"" + 2 + "\"}",new Handler() {
        HttpRequest.getInstance().getRequest(HttpUrl.MEN_ZHEN_GUA_HAO + "?param={\"mac\":\"" + deviceId + "\"}",new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.arg1 == -1) {
                    Toast.makeText(CallNumberActivity.this, "服务器水逆了...", Toast.LENGTH_SHORT).show();
                    System.out.println("*****   " + (String) msg.obj);
                } else if (msg.arg1 == 1) {
                    try {
                        JSONObject jsonObject = new JSONObject((String) msg.obj);
                        JSONArray jsonData = jsonObject.getJSONArray("rows");
                        for (int i = 0; i < jsonData.length(); i++) {
                            JSONObject jsonObject1 = jsonData.getJSONObject(i);
                            data.add(new CallNumberListItem(jsonObject1.getString("ROOMNAME"),jsonObject1.getString("DZ"),jsonObject1.getString("HJ"),jsonObject1.getString("JZ")));
                            but_ertongbjb.setText(jsonObject1.getString("NAME"));
                        }
                        Log.e("TAG","获取到的jsonObject +++"+jsonObject);
                        Log.e("TAG","获取到的jsonData +++"+jsonData);
                        Log.e("TAG","获取到的(String) msg.obj +++"+(String) msg.obj);
                        if (data.size() > 0) {
                            // TODO: 2018/2/5 0005 即有待读数据时，启动读音服务
                            for (int j = 0; j < data.size(); j++) {
                                if (!TextUtils.isEmpty(data.get(j).getHujiao())) {
//                                    text1.setText("请，" + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊，" + data.get(j).getZhunbei() + "准备就诊");
//                                    Log.e("TAG", "滚动条+++" + "请，" + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊，" + data.get(j).getZhunbei() + "准备就诊");
                                    text1.setText("请，" + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊");
                                    Log.e("TAG", "滚动条+++" + "请，" + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊");
                                    /////////////
                                    sp1 =getSharedPreferences("YuYin", MODE_PRIVATE);
                                    SharedPreferences.Editor edit = sp1.edit();
                                    edit.putString("yuYinValue",text1.getText().toString());
                                    edit.commit();
                                    //////////////
//                                    PlayMusic(R.raw.yuyin);
//                                    for (int k = 0; k <2 ; k++) {
//                                        textToSpeech.speak(text1.getText().toString(),
//                                    TextToSpeech.QUEUE_ADD, null);
                                        ////////////////////
                                        SharedPreferences sp2 = getSharedPreferences("YuYin", MODE_PRIVATE);
                                        final String yuYinValue =sp2.getString("yuYinValue","");
                                        Log.e("TAG","SharedPreferences sp2获得的语音朗读----------------------"+yuYinValue);
//                                        if (status2 == TextToSpeech.SUCCESS) {
//                                            int result = textToSpeech.setLanguage(Locale.CHINA);
//                                            if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
//                                                    && result != TextToSpeech.LANG_AVAILABLE){
//                                                Toast.makeText(getApplicationContext(), "TTS语音绑定失败！",
//                                                        Toast.LENGTH_SHORT).show();
//                                            }else {
//                                                textToSpeech.speak(yuYinValue,
//                                                        TextToSpeech.QUEUE_ADD, null);
//                                            }
//                                        }
                                        /////////////////
                                        ///////////////
                                        textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
                                            @Override
                                            public void onInit(int status) {
                                                if (status == textToSpeech.SUCCESS) {
                                                    int result = textToSpeech.setLanguage(Locale.CHINA);
                                                    if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
                                                            && result != TextToSpeech.LANG_AVAILABLE){
                                                        Toast.makeText(getApplicationContext(), "TTS暂时不支持这种语音的朗读！",
                                                                Toast.LENGTH_SHORT).show();
                                                    }else {
                                                        PlayMusic(R.raw.yuyin);
                                                        for (int k = 0; k <2 ; k++) {
                                                        textToSpeech.speak(yuYinValue,
                                                                TextToSpeech.QUEUE_ADD, null);}
                                                    }
                                                }
                                            }
                                        });
                                        //////////////////
                                        /////////////////////
                                        ////////////////////
//                                    }
                                }
//                                else if  (!TextUtils.isEmpty(data.get(j).getJiuzhen()))
//                                    text1.setText(data.get(j).getJiuzhen() + "在" + data.get(j).getZhenshi() + "就诊中，" + data.get(j).getZhunbei() + "准备就诊");
                            }
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callNumberAdapter.notifyDataSetChanged();
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
//    private String remberName=null;
//    private String huJiaoZhongName=null;
//    public void initWidgetValueFromRemote(JSONArray jsonArray) throws JSONException {
//            JSONObject jsonObject = jsonArray.getJSONObject(0);
//      if (!TextUtils.isEmpty(jsonObject.getString("HJ"))){
//          text1.setText("请"+jsonObject.getString("HJ")+"到"+jsonObject.getString("ROOMNAME")+"就诊"+","+jsonObject.getString("DZ")+"准备就诊");
//          Log.e("TAG","滚动条的内容-----------"+"请"+jsonObject.getString("HJ")+"到"+jsonObject.getString("ROOMNAME")+"就诊"+","+jsonObject.getString("DZ")+"准备就诊");
//          Log.e("TAG","滚动条的内容++++++++++++"+text1.getText().toString());
//          if (remberName==null){
//              PlayMusic(R.raw.yuyin);
//              textToSpeech.speak(text1.getText().toString(),
//                      TextToSpeech.QUEUE_ADD, null);
//              remberName = text1.getText().toString();
//          }else {
//              if(remberName.equals(text1.getText().toString()) ){
//                  textToSpeech.stop();
//              }else{
//                  PlayMusic(R.raw.yuyin);
//                  textToSpeech.speak(text1.getText().toString(),
//                          TextToSpeech.QUEUE_ADD, null);
//
//                  Log.e("TAG","输入框的内容+++++++++"+text1.getText().toString());
//                  remberName = text1.getText().toString();
//              }
//          }
//      }else if  (!TextUtils.isEmpty(jsonObject.getString("JZ")))
//          text1.setText(jsonObject.getString("JZ")+"在"+jsonObject.getString("ROOMNAME")+"就诊中，"+jsonObject.getString("DZ")+"准备就诊");
//    }
//    public class TimeThread extends Thread {
//        @Override
//        public void run () {
//            do {
//                try {
//                    Thread.sleep(1000);
//                    Message msg = new Message();
//                    msg.what = msgKey1;
//                    mHandler.sendMessage(msg);
//                }
//                catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            } while(true);
//        }
//    }
//    private Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage (Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case msgKey1:
////                    long sysTime = System.currentTimeMillis();
////                    CharSequence sysTimeStr = DateFormat.format("EEEE HH:mm:ss", sysTime);
////                    tv_mTime.setText(sysTimeStr);
//                    break;
//
//                default:
//                    break;
//            }
//        }
//    };

    /**
     * 展示所有从服务器上拉下来的数据
     */
    private void showAllMotherSonInfo() {
        RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
        mRecyclerview.setLayoutManager(manager);
        callNumberAdapter = new CallNumberAdapter(data,this);
        mRecyclerview.setAdapter(callNumberAdapter);
        mRecyclerview.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST));
        callNumberAdapter.setOnClickListener(new CallNumberAdapter.OnClickListener(){
            @Override
            public void onLongClickListener(int position) {
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (textToSpeech != null)
            textToSpeech.shutdown();
    }
    /**
     * 播放音乐，参数是资源id
     *
     * @param MusicId
     */
    private void PlayMusic(int MusicId) {
        music = MediaPlayer.create(this, MusicId);
        music.start();
    }
    public class TimeThreadjh extends Thread {
        @Override
        public void run () {
            do {
                try {
                    Thread.sleep(5000);
                    Message msg = new Message();
                    msg.what = msgKey2;
                    mHandlerjh.sendMessage(msg);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while(true);
        }
    }
    private Handler mHandlerjh = new Handler() {
        @Override
        public void handleMessage (Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case msgKey2:
                    getMotherYFXXTKFromRemote();
                    try {
                        Log.e("TAG","获取到的应用缓存大小*********************"+ DataCleanManager.getTotalCacheSize(CallNumberActivity.this));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                default:
                    break;
            }
        }
    };
    /**
     * 显示设置IP对话框
     */
    public void rename() {
        Log.v("TAG", "$$$$$$$$$$$$$inrename..");
        LayoutInflater factory = LayoutInflater.from(this);
        View textEntryView = factory.inflate(R.layout.dialog_hos_name, null);
        //内部局部类，只能访问方法的final类型的变量
        final EditText mname_edit = (EditText) textEntryView
                .findViewById(R.id.tv_acitivity_ip_set_hoename);
        // 不是用这个方法获取EditText的内容的
        // mname_edit.addTextChangedListener(mTextWatcher);

        // create a dialog
        new AlertDialog.Builder(CallNumberActivity.this)
                .setIcon(R.drawable.btn_certain_blue)
                .setTitle(R.string.soft_hosname_update_title)
                .setView(textEntryView)
                .setNegativeButton(R.string.soft_update_ip_later,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // TODO Auto-generated method stub

                            }

                        })
                .setPositiveButton(R.string.soft_update_ip_updatebtn,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // dialog.
                                // TODO Auto-generated method stub
                                Log.v("TAG", "你点击了确定");
                                if (!mname_edit.getText().toString().equals("")) {
                                    newName = mname_edit.getText().toString();
                                    tv_content.setText(newName);
                                    SharedPreferences sp =getSharedPreferences("HosSet", MODE_PRIVATE);
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString("hosValue",newName);
                                    edit.commit();
                                }
                                Log.v("TAG", "$$$$$btn.setText(newName);");
                            }

                        }).show();

    }
    /**
     * 监听Back键按下事件,方法2:
     * 注意:
     * 返回值表示:是否能完全处理该事件
     * 在此处返回false,所以会继续传播该事件.
     * 在具体项目中此处的返回值视情况而定.
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            System.out.println("按下了back键   onKeyDown()");
            System.exit(0);
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }
}
